COMMVOTE.Votes = {}
local DEBUG = true

concommand.Add("garc_votecomm", function( ply, cmd, args )

	if #args != 1 then
		return
	end
	
	local PlyIndex = tonumber( args[1] )
	local Comm = ents.GetByIndex( PlyIndex )
	local Team = ply:Team()
	
	if DEBUG then
		Msg( ply, "(", Team ,") voting for ", Comm, "(", Team ,")\n" )
	end
	
	if Team != TEAM_BLUE && Team != TEAM_RED then
		return
	end
	
	if !IsValid( Comm ) || Comm:Team() != Team then	
		return
	end
	
	COMMVOTE.Votes[ ply ] = Comm
	COMMVOTE:Recount()
	
end )

function COMMVOTE:Recount()

	local Count = {}
	
	for k, v in pairs( self.Votes ) do
		
		if !IsValid( k ) || !IsValid( v ) || v:Team() != k:Team() then
			table.remove( self.Votes, k )
		else
			
			if !Count[ v ] then
				Count[ v ] = 1
			else
				Count[ v ] = Count[v] + 1
			end
		
		end
		
	end
	
	for k, v in pairs( Count ) do
		
		if k.CommVotes != v then
			k.CommVotes = v
		end
	
	end
	
	PrintTable( Count )

end

function COMMVOTE:ElectComm()
	
	for _, v in pairs( team.GetValidTeams() ) do
		self:ElectCommTeam( v )
	end	

end

function COMMVOTE:ElectCommTeam( Team )
	
	local Players = team.GetPlayers( Team ) 
	local Highest = nil
	local HighestCount = 0
	
	for	_, v in pairs( Players ) do
	
		if v.CommVotes >= HighestCount then
			HighestCount = v.CommVotes
			Highest = v
		end
	
	end
	
	Msg("Found : ", Highest, " for team #", Team, "\n")
	
	if Highest then
		Highest:SetClass( "Commander" )
	end
	
end